import 'dart:math';

import 'package:easy_rich_text/easy_rich_text.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_model/cartoon_media_info.dart';
import 'package:tiktokadult/hj_page/cartoon_business/acg_widget_item.dart';
import 'package:tiktokadult/hj_page/cartoon_business/cartoon_recommend_logic.dart';
import 'package:tiktokadult/hj_page/cartoon_business/novel_detail_logic.dart';
import 'package:tiktokadult/hj_page/cartoon_business/widget/acg_expand_text.dart';
import 'package:tiktokadult/hj_page/cartoon_business/widget/acg_source_manager.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/routers/jump_router.dart';
import 'package:tiktokadult/tools_base/loading/l_error_widget.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';
import 'package:tiktokadult/tools_base/refresh/pull_refresh.dart';

//推荐页面
class CartoonRecommendPage extends StatefulWidget {
  final String? mediaId;
  final bool darkStyle;
  final EdgeInsetsGeometry? padding;
  final Function()? tapAction;
  final bool showHeader; //展示小说详情
  final NovelDetailLogic? mainLogic;
  final String recommengTitle;

  const CartoonRecommendPage({
    super.key,
    this.mediaId,
    this.darkStyle = false,
    this.tapAction,
    this.showHeader = false,
    this.mainLogic,
    this.padding = const EdgeInsets.only(left: 16, right: 16, top: 10),
    this.recommengTitle = '相关推荐',
  });

  @override
  State<CartoonRecommendPage> createState() => _CartoonRecommendPageState();
}

class _CartoonRecommendPageState extends State<CartoonRecommendPage> {
  late CartoonRecommendLogic logic;

  late String tag;

  @override
  void initState() {
    super.initState();
    tag = (widget.mediaId ?? '') + DateTime.now().millisecondsSinceEpoch.toString();
    logic = Get.put(CartoonRecommendLogic(mediaId: widget.mediaId), tag: tag);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CartoonRecommendLogic>(
      tag: tag,
      builder: (_) {
        if (_.dataList == null) return LoadingCenterWidget();
        if (_.dataList?.isEmpty == true)
          return CErrorWidget(
            retryOnTap: () => _.loadData(showLoading: true),
          );

        return Column(
          children: [
            Expanded(
              child: pullYsRefresh(
                onInit: (ctr) => _.refreshCtr = ctr,
                onLoading: (ctr) => _.loadMoreData(),
                enablePullDown: false,
                child: CustomScrollView(
                  slivers: <Widget>[
                    if (widget.showHeader && widget.mainLogic != null)
                      SliverToBoxAdapter(
                        child: _buildInfoView(widget.mainLogic!),
                      ),
                    SliverToBoxAdapter(
                        child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 16),
                      child: Text(
                        widget.recommengTitle,
                        style: textStyle(14, Colors.white.withOpacity(.9), FontWeight.w500),
                      ),
                    )),
                    SliverPadding(
                      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                      sliver: SliverGrid.builder(
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 3,
                          mainAxisSpacing: 12,
                          crossAxisSpacing: 6,
                          childAspectRatio: 111 / 188,
                        ),
                        itemCount: _.dataList?.length ?? 0,
                        itemBuilder: (context, index) {
                          CartoonMediaInfo? meidiaInfo = _.dataList?[index];
                          return AcgItemWidget(
                            info: meidiaInfo,
                            tapCallback: () {
                              widget.tapAction?.call();
                              if (meidiaInfo?.id == widget.mediaId) {
                                showToast('您当前正在观看此媒体');
                                return;
                              }
                              pushToCartoonPage(meidiaInfo);
                            },
                          );
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ),
            if (widget.showHeader && widget.mainLogic != null)
              InkWell(
                child: Container(
                    margin: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                    height: 44,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: AppColors.actionRed,
                      borderRadius: BorderRadius.circular(3),
                    ),
                    child: ChangeNotifierProvider(
                      create: (context) => widget.mainLogic!.manager,
                      child: Consumer<ACGSourceManager>(
                        builder: (context, value, child) => Text(
                          widget.mainLogic!.manager.actionTitle(),
                          style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
                        ),
                      ),
                    )),
                onTap: () => widget.mainLogic!.gotoPlay(index: widget.mainLogic!.manager.index),
              ),
          ],
        );
      },
    );
  }

  _buildInfoView(NovelDetailLogic _) {
    return Consumer<ACGSourceManager>(
      builder: (ctx, manager, child) => Column(
        children: [
          //详情
          if (_.model?.summary?.isNotEmpty == true) ...[
            12.sizeBoxH,
            Padding(
              padding: EdgeInsets.fromLTRB(0, 12, 0, 0),
              child: AcgShowMoreTextWidget(
                summary: _.model?.summary ?? '',
                maxWidth: Get.width - 10,
              ),
            )
          ],
          //标签
          if ((_.model?.tagDetails?.length ?? 0) != 0) ...[
            12.sizeBoxH,
            Wrap(
              spacing: 10,
              runSpacing: 0,
              children: List.generate(_.model?.tagDetails?.length ?? 0, (index) {
                final tag = _.model?.tagDetails?[index];
                return Container(
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(.1),
                    borderRadius: BorderRadius.circular(3),
                  ),
                  padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  child: Text(
                    '#${tag?.name ?? ''}',
                    style: TextStyle(
                      fontSize: 10,
                      color: Colors.white,
                    ),
                  ),
                );
              }),
            ),
          ],
          InkWell(
            onTap: () => _.episodesBottomSheet(),
            child: Row(
              children: [
                EasyRichText(
                  '${manager.mediaInfo?.getUpdateString ?? ''} ${manager.mediaInfo?.novelUpdateDesc ?? ''}',
                  defaultStyle: textStyle(14, Colors.white.withOpacity(.9), FontWeight.w500),
                  patternList: [
                    EasyRichTextPattern(
                      targetString: '${manager.mediaInfo?.novelUpdateDesc ?? ''}',
                      style: TextStyle(color: Color(0xffFFBB00), fontSize: 12, fontWeight: FontWeight.w500),
                    )
                  ],
                ),
                Spacer(),
                Image.asset('acg_menu_next.png'.acgImgPath, width: 16),
              ],
            ),
          ),
          6.sizeBoxH,
          ListView.separated(
            shrinkWrap: true,
            padding: EdgeInsets.zero,
            physics: NeverScrollableScrollPhysics(),
            itemCount: min(manager.allEpisodes.length, 3),
            separatorBuilder: (context, index) => Divider(
              height: .5,
              color: Colors.white.withOpacity(.1),
            ),
            itemBuilder: (BuildContext context, int index) {
              final epm = manager.allEpisodes[index];
              return InkWell(
                onTap: () => _.gotoPlay(index: index),
                child: Column(
                  children: [
                    12.sizeBoxH,
                    Row(
                      children: [
                        Text(
                          '第${epm.episodeNumber ?? 1}${_.model?.unit}\t${epm.name ?? ''}',
                          style: TextStyle(
                            color: manager.index == index ? Color(0xffFFBB00) : Color(0xff989898),
                            fontSize: 12,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                        Spacer(),
                        Container(
                          alignment: Alignment.center,
                          width: 56,
                          height: 26,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(3),
                            border: Border.all(width: 1, color: Color(0xffFFBB00)),
                          ),
                          child: Text(
                            '观看',
                            style: textStyle(12, Color(0xffFFBB00), FontWeight.w400),
                          ),
                        ),
                      ],
                    ),
                    12.sizeBoxH,
                  ],
                ),
              );
            },
          ),
          18.sizeBoxH,
          InkWell(
            onTap: () => _.episodesBottomSheet(),
            child: Container(
              height: 44,
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(.1),
                borderRadius: BorderRadius.circular(3),
              ),
              alignment: Alignment.center,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset('acg_novel_more.png'.acgImgPath, width: 16),
                  12.sizeBoxW,
                  Text(
                    '查看全部目录',
                    style: textStyle(16, Colors.white, FontWeight.w400),
                  ),
                ],
              ),
            ),
          ),
          18.sizeBoxH,
        ],
      ),
    ).paddingSymmetric(horizontal: 16);
  }
}
